//
//  ViewModelBootcamp.swift
//  FCSwiftUI
//
//  Created by 冯宣超 on 2023/3/12.
//

import SwiftUI

struct FruitModel: Identifiable {
    let id: String = UUID().uuidString
    let name: String
    let count: Int
}

/// ViewModel: 处理、准备一些与UI相关的数据的工作，使UI构建逻辑清晰，代码结构解偶性强
class FruitViewModel: ObservableObject {
    /// @State: 只用在继承自View的Struct中，声明是一个提供给下文使用的变量属性。
    /// @Published: 功能类似于@State，但应用于Class当中，不是View。View中可以访问这些Published的属性。
    @Published var fruitArray: [FruitModel] = []
    @Published var isLoading: Bool = false
    
    init() {
        getFruits()
    }
    
    func getFruits() {
        let fruit1 = FruitModel(name: "Orange", count: 1)
        let fruit2 = FruitModel(name: "Banana", count: 2)
        let fruit3 = FruitModel(name: "Watermelon", count: 88)
        
        isLoading = true
        DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
            self.fruitArray.append(fruit1)
            self.fruitArray.append(fruit2)
            self.fruitArray.append(fruit3)
            self.isLoading = false
        }
    }
    
    func deleteFruit(_ index: IndexSet) {
        fruitArray.remove(atOffsets: index)
    }
}

struct ViewModelBootcamp: View {
    //@State var fruitArray: [FruitModel] = []
    /// @ObservedObject: 声明该属性是可被观察的，否则在下文中对ViewModel的Published属性进行修改时，读取到的该属性值不会跟随变化。
    ///  @StateObject: 不同于@ObservedObject，当UI重新reload的时候，该属性不会被重新加载新数据，但ObservedObject会一起reload一遍。
    ///
    /// @StateObject -> 用于creat 或者 init。
    /// @ObservedObject -> 用于subview访问使用
    @StateObject var fruitViewModel: FruitViewModel = FruitViewModel()
    
    var body: some View {
        NavigationStack {
            List {
                if fruitViewModel.isLoading {
                    ProgressView()//这个地方有BUG，当subview回来的时候，他不显示了
                } else {
                    ForEach(fruitViewModel.fruitArray) { fruit in
                        HStack {
                            Text("\(fruit.count)")
                                .foregroundColor(.red)
                            Text(fruit.name)
                                .font(.headline)
                                .bold()
                        }
                    }
                    /// 传进来的参数恰巧是func的参数，可以省略不写，直接写调用函数的方法名
                    .onDelete(perform: fruitViewModel.deleteFruit)
                }
            }
            .listStyle(.grouped)
            .navigationTitle("Fruit List")
            .toolbar(content: {
                ToolbarItem(placement: .navigationBarTrailing) {
                    NavigationLink(destination: SecondScreen(fruitViewModel: fruitViewModel)) {
                        Image(systemName: "arrow.right")
                            .font(.title)
                    }
                }
            })
//            .onAppear {
//                fruitViewModel.getFruits()
//            }
        }
    }
}

private struct SecondScreen: View {
    @Environment(\.dismiss) var dismiss
    @ObservedObject var fruitViewModel: FruitViewModel
    
    var body: some View {
        ZStack {
            Color.green.ignoresSafeArea()
            
            VStack {
                ForEach(fruitViewModel.fruitArray) { fruit in
                    Text(fruit.name)
                        .foregroundColor(.white)
                        .font(.headline)
                }
            }
        }
    }
}

struct ViewModelBootcamp_Previews: PreviewProvider {
    static var previews: some View {
        ViewModelBootcamp()
    }
}
